package com.cortex.carambola.fetch;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.cortex.carambola.summary.CarambolaRequestSummary;
import com.cortex.carambola.summary.CarambolaSummary;
import com.cortex.carambola.utilities.MessagesLog;
import com.cortex.carambola.view.SummaryOnlineView;

import android.os.AsyncTask;
import android.util.Log;

public class FetchSummary {

	private OnStateChanged onStateChanged;
	private CarambolaSummary carambolaSummary;
	// request
	private static String REQUEST_SMMRY_URL = "http://api.smmry.com?"; 
	private static String REQUEST_API_KEY = "&SM_API_KEY=69D25D6E80";
	private static String REQUEST_SM_URL = "&SM_URL=";
	private static String REQUEST_SM_KEYWORDS = "&SM_KEYWORD_COUNT=";
	private static String REQUEST_SM_QUOTES = "&SM_QUOTE_AVOID";
	private static String REQUEST_SM_BREAK = "&SM_WITH_BREAK";
	private static String REQUEST_SM_SENTENCES = "&SM_LENGTH=";
	// answer
	private static String ANSWER_SM_NAME = "sm_api_title";
	private static String ANSWER_SM_CONTENT = "sm_api_content";
	private static String ANSWER_SM_CHARACTER = "sm_api_character_count";
	private static String ANSWER_SM_KEYWORDS = "sm_api_keyword_array";
	private static String ANSWER_SM_TYPE_ERROR = "sm_api_error";
	private static String ANSWER_SM_MESSAGE_ERROR = "sm_api_message";
	
	public void startFetching(CarambolaRequestSummary requestSummary){
		if(onStateChanged != null){
			onStateChanged.timeLoadStarted();
		}
		new StartSummaryThread().execute(requestSummary);
	}
	public void setOnStateChanged(OnStateChanged onStateChanged) {
		this.onStateChanged = onStateChanged;
	}
	private class StartSummaryThread extends AsyncTask<CarambolaRequestSummary, String, CarambolaSummary>{

		@Override
		protected CarambolaSummary doInBackground(CarambolaRequestSummary... params) {
			CarambolaRequestSummary requestSummary = params[0];
			HttpClient httpclient = new DefaultHttpClient();
			String request;
			String webSite = REQUEST_SM_URL + requestSummary.getUrl();
			String sentences = REQUEST_SM_SENTENCES + requestSummary.getSentencesNumber();
			String keywords = REQUEST_SM_KEYWORDS + requestSummary.getKeywordsNumber();
			request = REQUEST_SMMRY_URL + REQUEST_API_KEY + webSite + sentences + keywords;
			//request += SM_QUOTES;
			if(!requestSummary.isQuotes()){
				request += REQUEST_SM_QUOTES;
			}
			HttpPost httppost = new HttpPost(request);
			try {
				HttpResponse response = httpclient.execute(httppost);
				String responseBody = EntityUtils.toString(response.getEntity());
				carambolaSummary = createSummary(requestSummary, responseBody);
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			return carambolaSummary;
		}
		@Override
		protected void onProgressUpdate(String... values) {
			if(onStateChanged != null){
				onStateChanged.timeLoadCanceled(values[0]);
			}
		}
		@Override
		protected void onPostExecute(CarambolaSummary result) {
			if(onStateChanged != null){
				onStateChanged.timeLoadFinished(result);
			}
		}
		@Override
		protected void onCancelled() {
			super.onCancelled();
			if(onStateChanged != null){
				onStateChanged.timeLoadCanceled("summary canceled");
			}
		}
	}
	private CarambolaSummary createSummary(CarambolaRequestSummary requestSummary,String message){
		String name = "",summary = "",sentences = "",characters = "",url = "";
		boolean isQuotes = false;
		boolean isSummarySuccess = false;
		sentences = requestSummary.getSentencesNumber();
		isQuotes = requestSummary.isQuotes();
		url = requestSummary.getUrl();
		List<String> keywordsList = new ArrayList<String>();
		try {

			JSONObject jObject = new JSONObject(message);
			if(jObject.isNull(ANSWER_SM_TYPE_ERROR) && jObject.isNull(ANSWER_SM_MESSAGE_ERROR)){
				if(!jObject.isNull(ANSWER_SM_NAME)){
					name = jObject.getString(ANSWER_SM_NAME);
				}
				if(!jObject.isNull(ANSWER_SM_CONTENT)){
					summary = jObject.getString(ANSWER_SM_CONTENT);
				}
				if(!jObject.isNull(ANSWER_SM_CHARACTER)){
					characters = jObject.getString(ANSWER_SM_CHARACTER);
				}
				if(!jObject.isNull(ANSWER_SM_KEYWORDS)){
					JSONArray jsonArray = jObject.getJSONArray(ANSWER_SM_KEYWORDS);
					for (int i = 0; i < jsonArray.length(); i++) {
						keywordsList.add(jsonArray.optString(i));
					}
				}
				
				isSummarySuccess = true;
			}
			else{
				name = "summarized failed";
				summary = "please try again";
			}
		} catch (JSONException e) {
			Log.d(MessagesLog.APPLICATION_EXCEPTION,"error:" + e.getMessage());
		}
		return new CarambolaSummary(name,summary, 
				sentences,characters,keywordsList,isQuotes,url,true);
	}
	public interface OnStateChanged{
		void timeLoadStarted();
		void timeLoadFinished(CarambolaSummary summary);
		void timeLoadCanceled(String message);
	}
}
